<template>
  <div>
    <el-page-header title="返回" content="网址管理" @back="$router.go(-1)" />

    <el-row style="margin-top: 20px;">
      <el-col :span="8">
        <el-button type="primary" @click="showAddWebsiteDialog">添加网址</el-button>
      </el-col>
    </el-row>

    <el-table :data="websites" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="name" label="网址名称" />
      <el-table-column prop="url" label="URL地址" />
      <el-table-column prop="categoryName" label="所属分类" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="showEditWebsiteDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteWebsite(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <WebsiteForm
      v-model="showWebsiteDialog"
      :initial-values="currentWebsite"
      :categories="categories"
      @submit="handleWebsiteSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import websitesApi from '@/api/websites'
import categoriesApi from '@/api/categories'
import WebsiteForm from '@/components/WebsiteForm.vue'

interface Website {
  id?: number;
  name: string;
  url: string;
  categoryId?: number | null;
  categoryName?: string;
}

interface Category {
  id: number;
  name: string;
}

const websites = ref<Website[]>([])
const categories = ref<Category[]>([])
const showWebsiteDialog = ref(false)
const currentWebsite = ref<Website>({ name: '', url: '' })

const loadWebsites = async () => {
  try {
    const response = await websitesApi.getWebsites()
    websites.value = response.data.map((website: any) => ({
      ...website,
      categoryName: website.category?.name || ''
    }))
  } catch (error) {
    ElMessage.error('加载网址失败')
  }
}

const loadCategories = async () => {
  try {
    const response = await categoriesApi.getCategories()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('加载分类失败')
  }
}

const showAddWebsiteDialog = () => {
  currentWebsite.value = { name: '', url: '', categoryId: null }
  showWebsiteDialog.value = true
}

const showEditWebsiteDialog = (website: Website) => {
  currentWebsite.value = { ...website }
  showWebsiteDialog.value = true
}

const handleWebsiteSubmit = async (formData: Website) => {
  try {
    if (formData.id) {
      // 编辑网址
      await websitesApi.updateWebsite(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 添加网址
      await websitesApi.createWebsite(formData)
      ElMessage.success('创建成功')
    }
    await Promise.all([loadWebsites(), loadCategories()])
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteWebsite = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个网址吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await websitesApi.deleteWebsite(id)
    ElMessage.success('删除成功')
    await loadWebsites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(async () => {
  await Promise.all([loadWebsites(), loadCategories()])
})
</script>